package pl.edu.agh.neuraleconomy.core.ta.advice;

import java.util.Date;
import java.util.List;
import java.util.Map;

import pl.edu.agh.neuraleconomy.core.ta.indicator.RSICalculator;
import pl.edu.agh.neuraleconomy.model.exchange.Company;
import pl.edu.agh.neuraleconomy.model.exchange.Exchange;

public class RSIAdvisor extends IndicatorAdvisor {

	private int period;

	public RSIAdvisor(int period) {
		super();
		this.period = period;
		this.calculator = new RSICalculator(period);
	}

	public Advice getAdvice(Company company, Date date) {
		List<Exchange> data = getData(company, date);
		if (data.size() < period * 2) {
			logger.warn("Not enough data to give advice for company " + company.getName());
			return null;
		}

		//Collections.reverse(data); // has to be sorted ascending by date
		Map<Date, Double> rsi = calculator.calculate(data);

		Date last = data.get(data.size() - 1).getDate();
		
		return giveAdvice(company, rsi.get(last));
	}

	private List<Exchange> getData(Company company, Date date) {
		return exchangeDao.getLatestByCompanyIncludeDate(company.getId(), date, (long) period * 4);
	}
	
	private Advice giveAdvice(Company company, Double rsiValue){
		AdviceType type = AdviceType.STAY;
		int certainty = 0;
		
		if(rsiValue > 60){
			type = AdviceType.SELL;
			certainty = calculateCertainty(rsiValue - 70);
		}
		
		if(rsiValue < 40){
			type = AdviceType.BUY;
			certainty = calculateCertainty(30 - rsiValue);
		}
		
		return new Advice(company, type, certainty);
	}
	
	private int calculateCertainty(Double value){
		return 70 + value.intValue();
	}

}
